import { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import Nabar from '../../conpoment/Nabar';
import styles from './index.module.css';
// 订单状态类型
type OrderStatus = 'all' | 'pending' | 'approved' | 'cancelled';
// 患者信息接口
interface Patient {
  id: number;
  name: string;
  idNumber: string;
}
// 订单项目接口
interface OrderItem {
  id: number;
  name: string;
  type: 'medicine' | 'check' | 'test';
  price: number;
  quantity?: number;
  unit: string;
  tags?: string[];
}
// 订单接口
interface Order {
  id: number;
  items: OrderItem[];
  hospital: string;
  applicationTime: string;
  amount: number;
  status: 'pending' | 'approved' | 'rejected' | 'cancelled';
  reason?: string;
  patientName?: string;
  patientId?: string;
  applicationReason?: string;
}
function Index() {
  const navigate = useNavigate();
  const location = useLocation();
  const [activeTab, setActiveTab] = useState<OrderStatus>('all');
  const [showPatientModal, setShowPatientModal] = useState(false);
  const [selectedPatient, setSelectedPatient] = useState<Patient>({
    id: 1,
    name: '王小柯',
    idNumber: '2015****10'
  });
  const [orders, setOrders] = useState<Order[]>([]);
  // 模拟患者数据
  const patients: Patient[] = [
    { id: 1, name: '王小柯', idNumber: '2015****10' },
    { id: 2, name: '李玲玲', idNumber: '2015****10' }
  ];
  // 默认订单数据
  const defaultOrders: Order[] = [
    {
      id: 1,
      items: [
        { id: 1, name: '动态心电图', type: 'check', price: 150.00, unit: '次' },
        { id: 2, name: '血常规', type: 'test', price: 15.00, unit: '次' },
        { id: 3, name: '新冠预防中药', type: 'medicine', price: 11.80, quantity: 1, unit: '剂', tags: ['处方药'] }
      ],
      hospital: '四川省保健院北苑',
      applicationTime: '2020-01-01 10:30:20',
      amount: 201.00,
      status: 'pending',
      patientName: '王小柯',
      patientId: '2015****10'
    },
    {
      id: 2,
      items: [
        { id: 4, name: '胸部CT检查', type: 'check', price: 280.00, unit: '次' },
        { id: 5, name: '生化全套', type: 'test', price: 85.00, unit: '次' }
      ],
      hospital: '四川省保健院北苑',
      applicationTime: '2020-01-02 14:20:15',
      amount: 365.00,
      status: 'approved',
      patientName: '王小柯',
      patientId: '2015****10'
    },
    {
      id: 3,
      items: [
        { id: 6, name: '腹部B超检查', type: 'check', price: 120.00, unit: '次' },
        { id: 7, name: '尿常规检查', type: 'test', price: 12.00, unit: '次' }
      ],
      hospital: '四川省保健院北苑',
      applicationTime: '2020-01-03 09:15:30',
      amount: 132.00,
      status: 'rejected',
      reason: '检查项目不符合要求',
      patientName: '王小柯',
      patientId: '2015****10'
    }
  ];
  // 处理从申请页面传递的数据
  useEffect(() => {
    const state = location.state as any;
    if (state && state.newOrder) {
      const newOrder: Order = {
        id: Date.now(), // 使用时间戳作为ID
        items: state.newOrder.items || [],
        hospital: state.newOrder.hospital || '四川省保健院北苑',
        applicationTime: new Date().toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        }).replace(/\//g, '-'),
        amount: state.newOrder.amount || 0,
        status: 'pending',
        patientName: state.newOrder.patientName || selectedPatient.name,
        patientId: state.newOrder.patientId || selectedPatient.idNumber,
        applicationReason: state.newOrder.applicationReason
      };
      setOrders(prevOrders => [newOrder, ...prevOrders]);
      // 清除路由状态，避免重复添加
      window.history.replaceState({}, document.title);
    } else {
      // 如果没有新订单数据，使用默认数据
      setOrders(defaultOrders);
    }
  }, [location.state, selectedPatient]);

  // 初始化订单数据
  useEffect(() => {
    if (orders.length === 0) {
      setOrders(defaultOrders);
    }
  }, []);
  // 标签页配置
  const tabs = [
    { key: 'all', label: '全部' },
    { key: 'pending', label: '待审核' },
    { key: 'approved', label: '已审核' },
    { key: 'cancelled', label: '已取消' }
  ];
  // 根据当前标签页过滤订单
  const filteredOrders = orders.filter(order => {
    if (activeTab === 'all') return true;
    if (activeTab === 'pending') return order.status === 'pending';
    if (activeTab === 'approved') return order.status === 'approved';
    if (activeTab === 'cancelled') return order.status === 'cancelled' || order.status === 'rejected';
    return true;
  });
  // 获取状态标签样式
  const getStatusStyle = (status: string) => {
    switch (status) {
      case 'pending':
        return styles.statusPending;
      case 'approved':
        return styles.statusApproved;
      case 'rejected':
        return styles.statusRejected;
      case 'cancelled':
        return styles.statusCancelled;
      default:
        return styles.statusDefault;
    }
  };
  // 获取状态文本
  const getStatusText = (status: string) => {
    switch (status) {
      case 'pending':
        return '待审核';
      case 'approved':
        return '审核通过';
      case 'rejected':
        return '审核驳回';
      case 'cancelled':
        return '已取消';
      default:
        return '未知状态';
    }
  };
  // 处理标签页切换
  const handleTabChange = (tab: OrderStatus) => {
    setActiveTab(tab);
  };
  // 处理患者选择
  const handlePatientSelect = (patient: Patient) => {
    setSelectedPatient(patient);
    setShowPatientModal(false);
  };
  // 处理添加患者
  const handleAddPatient = () => {
    console.log('添加患者');
    setShowPatientModal(false);
  };
  // 处理订单操作
  const handleOrderAction = (order: Order, action: string) => {
    switch (action) {
      case 'cancel':
        console.log('取消申请', order.id);
        break;
      case 'pay':
        console.log('去支付', order.id);
        navigate('/payment', { state: { order } });
        break;
      case 'view':
        console.log('查看详情', order.id);
        break;
      default:
        break;
    }
  };
  return (
    <div className={styles.container}>
      {/* 头部导航 */}
      <Nabar title="开单记录" sticky={false} />
      {/* 右侧图标 */}
      <div className={styles.headerRight}>
        <div className={styles.headerIcon}>⋯</div>
        <div className={styles.headerIcon}>◎</div>
      </div>

      {/* 标签页 */}
      <div className={styles.tabs}>
        {tabs.map((tab) => (
          <div
            key={tab.key}
            className={`${styles.tab} ${activeTab === tab.key ? styles.activeTab : ''}`}
            onClick={() => handleTabChange(tab.key as OrderStatus)}
          >
            {tab.label}
          </div>
        ))}
      </div>
      {/* 患者信息卡片 */}
      <div className={styles.patientCard}>
        <div className={styles.patientInfo}>
          <div className={styles.patientName}>{selectedPatient.name}</div>
          <div className={styles.patientId}>{selectedPatient.idNumber}</div>
        </div>
        <div 
          className={styles.switchBtn}
          onClick={() => setShowPatientModal(true)}
        >
          <span className={styles.switchIcon}>⫸</span>
          <span className={styles.switchText}>切换</span>
        </div>
      </div>
      {/* 订单列表 */}
      <div className={styles.orderList}>
        {filteredOrders.length > 0 ? (
          filteredOrders.map((order) => (
            <div key={order.id} className={styles.orderCard}>
              {/* 订单标题和状态 */}
              <div className={styles.orderHeader}>
                <div className={styles.orderTitle}>
                  {order.items.map(item => item.name).join('、')}
                  {order.items.length > 3 && '...'}
                </div>
                <div className={`${styles.statusTag} ${getStatusStyle(order.status)}`}>
                  {getStatusText(order.status)}
                </div>
              </div>

              {/* 订单信息 */}
              <div className={styles.orderInfo}>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>申请医院</span>
                  <span className={styles.infoValue}>{order.hospital}</span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>申请时间</span>
                  <span className={styles.infoValue}>{order.applicationTime}</span>
                </div>
                <div className={styles.infoRow}>
                  <span className={styles.infoLabel}>开单金额</span>
                  <span className={styles.infoValue}>¥ {order.amount.toFixed(2)}</span>
                </div>
              </div>
              {/* 操作按钮 */}
              <div className={styles.orderActions}>
                {order.status === 'pending' && (
                  <button 
                    className={styles.cancelBtn}
                    onClick={() => handleOrderAction(order, 'cancel')}
                  >
            
                    取消申请
                  </button>
                )}
                {order.status === 'approved' && (
                  <button 
                    className={styles.payBtn}
                    onClick={() => handleOrderAction(order, 'pay')}
                  >
                    去支付
                  </button>
                )}
                {order.status === 'rejected' && (
                  <div className={styles.rejectedInfo}>
                    <span className={styles.rejectedText}>审核驳回</span>
                    {order.reason && (
                      <span className={styles.reasonText}>原因: {order.reason}</span>
                    )}
                  </div>
                )}
              </div>
            </div>
          ))
        ) : (
          <div className={styles.emptyState}>
            <div className={styles.emptyIcon}>📋</div>
            <div className={styles.emptyText}>暂无订单记录</div>
            <div className={styles.emptySubText}>您还没有相关的订单记录</div>
          </div>
        )}
      </div>
      

      {/* 患者选择模态框 */}
      {showPatientModal && (
        <div className={styles.modalOverlay} onClick={() => setShowPatientModal(false)}>
          <div className={styles.modal} onClick={(e) => e.stopPropagation()}>
            <div className={styles.modalHeader}>
              <div className={styles.modalTitle}>选择就诊人</div>
              <div 
                className={styles.modalClose}
                onClick={() => setShowPatientModal(false)}
              >
                ×
              </div>
            </div>
            <div className={styles.patientList}>
              {patients.map((patient) => (
                <div
                  key={patient.id}
                  className={`${styles.patientItem} ${
                    selectedPatient.id === patient.id ? styles.selectedPatient : ''
                  }`}
                  onClick={() => handlePatientSelect(patient)}
                >
                  <div className={styles.patientName}>{patient.name}</div>
                  <div className={styles.patientId}>{patient.idNumber}</div>
                </div>
              ))}
            </div>
            <div className={styles.modalFooter}>
              <button 
                className={styles.addPatientBtn}
                onClick={handleAddPatient}
              >
                添加就诊人
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
export default Index;
